package es.udima.geo.geoserver.persistence;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import es.udima.geo.geoserver.entities.UserActivityFilter;
import es.udima.geo.geoserver.entities.UserActivityLog;

public class UserActivityLogDAO extends GenericDAO {

    public UserActivityLogDAO() {
    }

    /**
     * 
     * @param user
     */
    public void createUserActivity(UserActivityLog activity) {
	EntityManager em = createEntityManager();
	EntityTransaction et = em.getTransaction();
	et.begin();
	em.persist(activity);
	et.commit();
	em.close();
    }

    /**
     * Finaliza la actividad actualizando el dato success a true
     * 
     * @param activityId
     */
    public void terminateUserActivity(String activityId) {
	EntityManager em = createEntityManager();
	EntityTransaction et = em.getTransaction();
	UserActivityLog ua = em.find(UserActivityLog.class, activityId);
	if (ua != null) {
	    ua.setSuccess(true);
	    et.begin();
	    em.merge(ua);
	    et.commit();
	}
	em.close();
    }

    /**
     * 
     * @return
     */
    public List<UserActivityLog> retrieveUserActivity(UserActivityFilter filter) {

	EntityManager em = createEntityManager();

	List<UserActivityLog> res = new ArrayList<UserActivityLog>();

	try {
	    CriteriaBuilder cb = em.getCriteriaBuilder();
	    CriteriaQuery<UserActivityLog> cq = cb.createQuery(UserActivityLog.class);
	    Root<UserActivityLog> r = cq.from(UserActivityLog.class);

	    Predicate pred = cb.conjunction();

	    if (filter.getUserId() != null) {
		Predicate pd = cb.equal(r.get("userId"), filter.getUserId());
		pred = cb.and(pred, pd);
	    }

	    if (filter.getInitDate() != null) {
		Calendar d = Calendar.getInstance();
		d.setTime(filter.getInitDate().getTime());
		Predicate pd = cb.greaterThanOrEqualTo(r.get("timestamp").as(Calendar.class), d);
		pred = cb.and(pred, pd);
	    }

	    if (filter.getEndDate() != null) {
		Calendar d = Calendar.getInstance();
		d.setTime(filter.getEndDate().getTime());
		Predicate pd = cb.lessThanOrEqualTo(r.get("timestamp").as(Calendar.class), d);
		pred = cb.and(pred, pd);
	    }

	    cq.select(r).where(pred);
	    TypedQuery<UserActivityLog> tq = em.createQuery(cq);
	    res = tq.getResultList();
	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    em.close();
	}

	return res;
    }
}
